﻿using System;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web.UI;
using GoFishWeb.Models;

namespace GoFishWeb
{
    public partial class GamePlay : Page
    {
        private const string SessionGameKey = "gameId";
        private const int TimeOutInMinutes = 15;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack) return;

            if (Request.UrlReferrer == null) Response.Redirect("~/Default.aspx"); 

            ToggleVisibilityForGamePlay(false);

            try
            {
                var gameId = Convert.ToInt32(Request["game"]);

                Session.Add(SessionGameKey, gameId);

                using (var db = new GoFishContext())
                {
                    switch (Request["type"])
                    {
                        case "join":
                        {
                            var game = GetGame(db);
                            UpdateUI(game);
                            db.SaveChanges();
                        }
                            break;
                        case "rejoin":
                        {
                            var game = GetGame(db);
                            UpdateUI(game);
                        }
                            break;
                    }
                }
            }
            catch (NullReferenceException)
            {
                lblErrorMessage.Visible = true;
                lblErrorMessage.Text = "Game doesn't exist. Choose new game.";
                StartButton.Enabled = false;
            }
        }

        protected void PlayButton_Click(object sender, EventArgs e)
        {
            using (var db = new GoFishContext())
            {
                try
                {
                    var game = GetGame(db);

                    try
                    {
                        IsValidCard();
                        IsValidPlayer();

                        game.AskForCard(txtCard.Text, User.Identity.Name, txtPlayer.Text);
                        lblErrorMessage.Visible = false;
                        lblErrorMessage.Text = String.Empty;
                    }
                    catch (Exception exception)
                    {
                        lblErrorMessage.Visible = true;
                        lblErrorMessage.Text = exception.Message;
                    }

                    txtCard.Text = String.Empty;
                    txtPlayer.Text = String.Empty;

                    EvaluateGame(game, db);

                    UpdateUI(game);

                    db.SaveChanges();
                }
                catch (NullReferenceException)
                {
                    lblErrorMessage.Visible = true;
                    lblErrorMessage.Text = "Game doesn't exist. Choose new game.";
                    StartButton.Enabled = false;
                }
            }
        }

        protected void StartButton_Click(object sender, EventArgs e)
        {
            using (var db = new GoFishContext())
            {
                try
                {
                    var game = GetGame(db);
                    if (game.GetPlayerCount() >= 3 && !game.IsGameStarted)
                    {
                        game.StartGame();
                        UpdateUI(game);
                        db.SaveChanges();
                    }
                    else UpdateUI(game);
                }
                catch (NullReferenceException)
                {
                    lblErrorMessage.Visible = true;
                    lblErrorMessage.Text = "Game doesn't exist. Choose new game.";
                    StartButton.Enabled = false;
                }
            }
        }

        private void IsValidCard()
        {
            var match = Regex.Match(txtCard.Text, Card.CardRankRegEx, RegexOptions.IgnoreCase).Success;
            if (!match)
                throw new ArgumentException(string.Format("{0} is not a valid card.", txtCard.Text.Equals("") ? "Blank" : txtCard.Text));
        }

        private void IsValidPlayer()
        {
            var match = Regex.Match(txtPlayer.Text, "^[0-9a-zA-Z]*$", RegexOptions.IgnoreCase).Success;
            if (!match)
                throw new ArgumentException(string.Format("{0} is not a valid player.", txtPlayer.Text.Equals("") ? "Blank" : txtPlayer.Text));
        }

        protected void Timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                using (var db = new GoFishContext())
                {
                    var game = GetGame(db);
                    UpdateUI(game);

                    if (game.IsTimedOut(TimeOutInMinutes))
                    {
                        UpdateUI(game);
                        db.SaveChanges();
                    }
                }
            }
            catch (NullReferenceException)
            {
                lblErrorMessage.Visible = true;
                lblErrorMessage.Text = "Game doesn't exist. Choose new game.";
                StartButton.Enabled = false;
            }
        }

        private void EvaluateGame(GoFishGame game, GoFishContext db)
        {
            if (!game.IsGameOver) return;

            PlayButton.Enabled = false;
            var winners = game.GetWinners().ToList();

            if (winners.Count() > 1)
            {
                foreach (var goFishPlayer in winners)
                {
                    var record = db.PlayerRecords.FirstOrDefault(r => r.UserName.Equals(goFishPlayer.Name));
                    if (record != null)
                        record.Ties++;    
                }
            }
            else
            {
                var player = winners[0];
                var record = db.PlayerRecords.FirstOrDefault(r => r.UserName.Equals(player.Name));
                if (record != null)
                    record.Wins++;
            }

            db.SaveChanges();

            foreach (var loser in game.Players.Where(p => !winners.Any(w => w.Name.Equals(p.Name))))
            {
                var record = db.PlayerRecords.FirstOrDefault(r => r.UserName.Equals(loser.Name));
                if (record != null)
                    record.Losses++;
                db.SaveChanges();
            }
        }

        private void UpdateUI(GoFishGame game)
        {
            if (game.IsInProgress())
            {
                ToggleVisibilityForGamePlay(true);

                StartButton.Enabled = false;

                HandListBox.Items.Clear();
                foreach (var card in game.GetPlayer(User.Identity.Name).Hand.OrderBy(x => x.Rank))
                {
                    HandListBox.Items.Add(card.ToString());
                }

                BooksListBox.Items.Clear();
                foreach (var goFishBook in game.Books)
                {
                    BooksListBox.Items.Add(goFishBook.ToString());
                }

                if (game.CurrentPlayer != null)
                {
                    lblPlayersTurn.Text = game.CurrentPlayer.Name;
                }

                PlayButton.Enabled = game.IsCurrentPlayer(User.Identity.Name);

                lblCardsLeft.Text = game.Deck.Count.ToString(CultureInfo.InvariantCulture);

                if (game.IsTimeOut)
                {
                    PlayButton.Enabled = false;
                }
            }
            else
            {
                ToggleVisibilityForGamePlay(false);

                if (!game.IsTimeOut)
                {
                    StartButton.Enabled = true;
                }
                PlayButton.Enabled = false;
            }

            GameMovesListBox.Items.Clear();
            foreach (var goFishMove in game.Moves.OrderByDescending(m => m.OccurredOn))
            {
                GameMovesListBox.Items.Add(goFishMove.Description);
            }
        }

        private void ToggleVisibilityForGamePlay(Boolean isVisible)
        {
            lblHand.Visible = isVisible;
            HandListBox.Visible = isVisible;
            lblCurrentPlayer.Visible = isVisible;
            lblPlayersTurn.Visible = isVisible;
            lblCardsInDeck.Visible = isVisible;
            lblCardsLeft.Visible = isVisible;
            PlayButton.Visible = isVisible;
            lblPlayersTurn.Visible = isVisible;
            lblCardsLeft.Visible = isVisible;
            lblCardChoice.Visible = isVisible;
            lblPlayerChoice.Visible = isVisible;
            txtPlayer.Visible = isVisible;
            txtCard.Visible = isVisible;

            StartButton.Visible = !isVisible;
        }

        private GoFishGame GetGame(GoFishContext db)
        {
            var gameId = (int) Session[SessionGameKey];
            return db.Games.FirstOrDefault(g => g.Id == gameId);
        }
    }
}